package com.dmooo.ymx.activity;

import android.Manifest;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dmooo.ymx.CaiNiaoApplication;
import com.dmooo.ymx.R;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.mall.MallGoodsDetailsActivity;
import com.dmooo.ymx.utils.DateUtils;
import com.dmooo.ymx.utils.StartActivityUtil;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leolin.shortcutbadger.ShortcutBadger;
import pub.devrel.easypermissions.EasyPermissions;

public class ChatActivity extends BaseActivity {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_name)
    TextView txt_name;
    @BindView(R.id.txt_price)
    TextView txt_price;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.ll_goods)
    LinearLayout ll_goods;
    public static String current_id = "";

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void initData() {
        if(getIntent().getExtras().getString("goods_id")!=null){
            ll_goods.setVisibility(View.VISIBLE);
            Glide.with(this).load(getIntent().getExtras().getString("goods_img")).into(img);
            txt_name.setText(getIntent().getExtras().getString("goods_name"));
            txt_price.setText(getIntent().getExtras().getString("goods_price"));
        }
        txtTitle.setText(getIntent().getExtras().getString("name"));
        findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_goods.setVisibility(View.GONE);
            }
        });
        EaseChatFragment chatFragment = new EaseChatFragment();
        findViewById(R.id.txt_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
                message.addBody(new EMTextMessageBody("你好,我想咨询商品: " +getIntent().getExtras().getString("goods_name")+"goods_id/"+getIntent().getExtras().getString("goods_id")));
                message.setChatType(EMMessage.ChatType.Chat);
                message.setTo(getIntent().getExtras().getString("uuid"));
                message.setAttribute("nick", (CaiNiaoApplication.getUserInfoBean().user_detail.nickname == null || "".equals(CaiNiaoApplication.getUserInfoBean().user_detail.nickname) || "null".equals(CaiNiaoApplication.getUserInfoBean().user_detail.nickname)) ? CaiNiaoApplication.getUserInfoBean().user_msg.phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2") : CaiNiaoApplication.getUserInfoBean().user_detail.nickname);
                message.setAttribute("avatar", CaiNiaoApplication.getUserInfoBean().user_detail.avatar);
                message.setDirection(EMMessage.Direct.SEND);
                EMClient.getInstance().chatManager().sendMessage(message);
                chatFragment.getList().refresh();
                ll_goods.setVisibility(View.GONE);
            }
        });
        current_id = getIntent().getExtras().getString("uuid");
        if ("0".equals(SPUtils.getStringData(this, DateUtils.format_yyyy_MM_dd(new Date())+getIntent().getExtras().getString("uuid"), "0"))) {
            SPUtils.saveStringData(this, DateUtils.format_yyyy_MM_dd(new Date())+getIntent().getExtras().getString("uuid"), "1");
            EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            message.addBody(new EMTextMessageBody("您好,我是客服" + getIntent().getExtras().getString("name") + ",请问有什么可以帮助您的吗?"));
            message.setFrom(getIntent().getExtras().getString("uuid"));
            message.setChatType(EMMessage.ChatType.Chat);
            message.setAttribute("nick", getIntent().getExtras().getString("name"));
            message.setAttribute("avatar", "");
            message.setDirection(EMMessage.Direct.RECEIVE);
            message.setUnread(false);
            EMClient.getInstance().chatManager().sendMessage(message);
        }
        if (getIntent().getExtras().getString("msg") != null) {
//            EMMessage sendMessage = EMMessage.createSendMessage(EMMessage.Type.TXT);
//            sendMessage.addBody(new EMTextMessageBody(getIntent().getExtras().getString("msg")));
//            sendMessage.setTo(current_id);
//            sendMessage.setChatType(EMMessage.ChatType.Chat);
//            sendMessage.setAttribute("nick", CaiNiaoApplication.getUserInfoBean().user_detail.nickname);
//            sendMessage.setAttribute("avatar",CaiNiaoApplication.getUserInfoBean().user_detail.avatar);
//            sendMessage.setDirection(EMMessage.Direct.SEND);
//            sendMessage.setUnread(false);
//            EMClient.getInstance().chatManager().sendMessage(sendMessage);
//            sendMessage = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
//            sendMessage.addBody(new EMImageMessageBody(new File(getIntent().getExtras().getString("image"))));
//            sendMessage.setTo(current_id);
//            sendMessage.setChatType(EMMessage.ChatType.Chat);
//            sendMessage.setAttribute("nick",CaiNiaoApplication.getUserInfoBean().user_detail.nickname);
//            sendMessage.setAttribute("avatar",CaiNiaoApplication.getUserInfoBean().user_detail.avatar);
//            sendMessage.setDirection(EMMessage.Direct.SEND);
//            sendMessage.setUnread(false);
//            EMClient.getInstance().chatManager().sendMessage(sendMessage);
        }
        chatFragment.hideTitleBar();
        chatFragment.setChatFragmentHelper(new EaseChatFragment.EaseChatFragmentHelper() {
            @Override
            public void onSetMessageAttributes(EMMessage message) {
                // 通过扩展属性，将userPic和userName发送出去。
                message.setAttribute("avatar", CaiNiaoApplication.getUserInfoBean().user_detail.avatar);
                message.setAttribute("userId", CaiNiaoApplication.getUserInfoBean().user_msg.uid);
                message.setAttribute("nick", (CaiNiaoApplication.getUserInfoBean().user_detail.nickname == null || "".equals(CaiNiaoApplication.getUserInfoBean().user_detail.nickname) || "null".equals(CaiNiaoApplication.getUserInfoBean().user_detail.nickname)) ? CaiNiaoApplication.getUserInfoBean().user_msg.phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2") : CaiNiaoApplication.getUserInfoBean().user_detail.nickname);
            }

            @Override
            public void onEnterToChatDetails() {

            }

            @Override
            public void onAvatarClick(String username) {
//                startActivity(new Intent(GroupChatActivity.this,StuPicActivity.class).putExtra("uid",username));
            }

            @Override
            public void onAvatarLongClick(String username) {

            }

            @Override
            public boolean onMessageBubbleClick(EMMessage message) {
                if (message.getType() == EMMessage.Type.TXT) {
                    EMTextMessageBody body = (EMTextMessageBody) message.getBody();
                    if (body.getMessage().contains("goods_id/")) {
                        Bundle bundle = new Bundle();
                        bundle.putString("goods_id", body.getMessage().substring(body.getMessage().indexOf("goods_id/"), body.getMessage().length()).replace("goods_id/", ""));
                        StartActivityUtil.startActivity(ChatActivity.this, MallGoodsDetailsActivity.class,bundle);
                    } else if (body.getMessage().contains("service_id/")) {
                        Bundle bundle = new Bundle();
                        bundle.putString("service_id", body.getMessage().substring(body.getMessage().indexOf("service_id/"), body.getMessage().length()).replace("service_id/", ""));
//                        StartActivityUtil.startActivity(ChatActivity.this,ServiceDetailActivity.class,bundle);
                    }
                }
                return false;
            }

            @Override
            public void onMessageBubbleLongClick(EMMessage message) {

            }

            @Override
            public boolean onExtendMenuItemClick(int itemId, View view) {
                return false;
            }

            @Override
            public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
                return null;
            }
        });
        Bundle args = new Bundle();
        args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        args.putString(EaseConstant.EXTRA_USER_ID, getIntent().getExtras().getString("uuid"));
        chatFragment.setArguments(args);
        try {
            getSupportFragmentManager().beginTransaction().add(R.id.ll_container, chatFragment).commit();
            int count = EMClient.getInstance().chatManager().getUnreadMessageCount();
            ShortcutBadger.applyCount(this, count); //for 1.1.4+
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!checkPermission(Permission.READ_PHONE_STATE)) {
//            requestPermission(Permission.READ_PHONE_STATE, "手机存储权限");
//            return;
//        }
//        if (!checkPermission(Permission.WRITE_EXTERNAL_STORAGE)) {
//            requestPermission(Permission.WRITE_EXTERNAL_STORAGE, "手机存储权限");
//            return;
//        }
        String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (!EasyPermissions.hasPermissions(this, mPermissionList)) {
            EasyPermissions.requestPermissions((Activity) this, "保存图片需要读取sd卡的权限", 1, mPermissionList);
        }
//        if (!checkPermission(Permission.ACCESS_FINE_LOCATION)) {
//            requestPermission(Permission.CAMERA, "定位权限");
//            return;
//        }
//        if (!checkPermission(Permission.ACCESS_COARSE_LOCATION)) {
//            requestPermission(Permission.CAMERA, "定位权限");
//            return;
//        }
    }

    @OnClick(R.id.txt_back)
    public void onViewClicked() {
        finish();
    }
}
